package command

import (
        "errors"
        "fmt"
        "github.com/spf13/cobra"
		"os"
		"io/ioutil"
        "os/exec"
        "runtime"
        "strings"
)

var rootCmd = &cobra.Command{
        Use:   "admin",
        Short: "admin",
        Long:  `思晓自习室自主学习平台`,
        Args:  args,
        Run: func(cmd *cobra.Command, args []string) {

        },
}

var stopCmd = &cobra.Command{
	Use:   "stop",
	Short: "停止http服务",
	Run: func(cmd *cobra.Command, args []string) {
			pids, err := ioutil.ReadFile("admin.sock")
			if err != nil {
					return
			}
			pidSlice := strings.Split(string(pids), ",")
			var command *exec.Cmd
			for _, pid := range pidSlice {
					if runtime.GOOS == "windows" {
							command = exec.Command("taskkill.exe", "/f", "/pid", pid)
					} else {
							command = exec.Command("kill", pid)
					}
					command.Start()
			}
	},
}


func args(cmd *cobra.Command, args []string) error {
	if len(args) < 1 {

			return errors.New("至少需要一个参数!")
	}
	return nil
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
			fmt.Println(err)
			os.Exit(1)
	}
}
		
func init() {
	rootCmd.AddCommand(serverCmd)
	// rootCmd.AddCommand(installCmd)
	rootCmd.AddCommand(stopCmd)
}
